package cn.songtx.iot.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Service;

@Service
public class MqttGateWayService {

    @Autowired
    private MessageChannel mqttOutboundChannel;

    /**
     * 发布消息,不带Qos,使用默认值0
     *
     * @param topic   主题
     * @param payload 消息内容
     */
    public void publishMqtt(String topic, String payload) {
        // 创建消息头访问器
        publishMqtt(topic, 0, payload);

    }

    /**
     * 发布消息,带qos
     *
     * @param topic   主题
     * @param qos     qos
     * @param payload 消息内容
     */

    public void publishMqtt(String topic, int qos, String payload) {
        // 创建消息头访问器
        MessageHeaderAccessor accessor = MessageHeaderAccessor.getMutableAccessor(new GenericMessage<>(payload));
        // 设置 topic 到消息头
        accessor.setHeader(MqttHeaders.TOPIC, topic);
        // 设置 qos 到消息头
        accessor.setHeader(MqttHeaders.QOS, qos);
        // 获取消息头
        MessageHeaders headers = accessor.getMessageHeaders();
        // 创建消息
        GenericMessage<String> message = new GenericMessage<>(payload, headers);
        mqttOutboundChannel.send(message);
    }
}
